package com.xxq.gulimall.product.service.impl;

import com.xxq.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.xxq.gulimall.product.dao.AttrGroupDao;
import com.xxq.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.xxq.gulimall.product.entity.AttrGroupEntity;
import com.xxq.gulimall.product.entity.CategoryEntity;
import com.xxq.gulimall.product.service.AttrAttrgroupRelationService;
import com.xxq.gulimall.product.service.AttrGroupService;
import com.xxq.gulimall.product.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xxq.common.utils.PageUtils;
import com.xxq.common.utils.Query;

import com.xxq.gulimall.product.dao.AttrDao;
import com.xxq.gulimall.product.entity.AttrEntity;
import com.xxq.gulimall.product.service.AttrService;

import javax.annotation.Resource;


@Slf4j
@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {
    @Resource
    private CategoryService categoryService;
    @Resource
    private AttrAttrgroupRelationService relationService;
    @Resource
    private AttrDao attrDao;
    @Resource
    private AttrGroupDao attrGroupDao;
    @Resource
    private AttrAttrgroupRelationDao relationDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override // TODO 多表查询
    public PageUtils queryPageByCatelogId(Map<String, Object> params, Long catelogId) {
        Integer page = 1;
        Integer limit = 10;
        if (params.get("page") != null)
            page = Integer.valueOf(params.get("page").toString());
        if (params.get("limit") != null)
            limit = Integer.valueOf(params.get("limit").toString());

        String sidx = "attr_id";
        String order = "desc";
        if (params.get("sidx") != null)
            sidx = params.get("sidx").toString();
        if (params.get("order") != null)
            order = params.get("order").toString();

        //查询总记录数
        Integer totalCount = attrDao.queryTotalCountByCatelogId(catelogId);
        //查询分类名
        String catelogName = categoryService.getCatelogName(catelogId);

        List<AttrEntity> attrEntities = attrDao.queryPageByCatelogIdBySql(page, limit, sidx, order, catelogId);

        attrEntities.forEach(entity -> {
            entity.setCatelogName(catelogName);
        });

        return new PageUtils(attrEntities, totalCount.longValue(),
                limit.longValue(), page.longValue());
    }

    public void test(Map<String, Object> params, Long catelogId) {
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (catelogId != 0L)
            queryWrapper.eq("catelog_id", catelogId);
        String key = (String) params.get("key");
        if (key != null && !key.isEmpty()) {
            queryWrapper.like("attr_name", key).or()
                    .like("value_select", key);
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);
        List<AttrEntity> attrEntities = page.getRecords();

        //查询分类名
        String catelogName = categoryService.getCatelogName(catelogId);

        attrEntities.forEach(entity -> {
            entity.setCatelogName(catelogName);
        });
    }

    @Override // TODO 暂无
    public void saveOrUpdateWithAttrGroupId(AttrEntity attr, String bool) {
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();

        if ("save".equals(bool)) {
            baseMapper.insert(attr);
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationService.save(relationEntity);
        } else {
            baseMapper.updateById(attr);
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            relationService.updateById(relationEntity);
        }
    }

    @Override // TODO 多表查询
    public List<AttrEntity> getRelation(Long attrGroupId) {
        return attrDao.getRelation(attrGroupId);
    }

    @Override // TODO 自连接
    public AttrEntity getByIdWithCatelogPath(Long attrId) {
        AttrEntity attrEntity = baseMapper.selectById(attrId);
        // 查询分类完整路径
        Long[] catelogPath = categoryService.getCatelogPath(attrEntity.getCatelogId());
        attrEntity.setCatelogPath(catelogPath);

        // 获取分组id
        AttrAttrgroupRelationEntity relationEntity = relationService.queryByAttrId(attrId);
        attrEntity.setAttrGroupId(relationEntity.getAttrGroupId());

        return attrEntity;
    }

    @Override // 获取当前分组没有关联的所有属性
    public PageUtils getNoRelationAttr(Map<String, Object> params, Long attrgroupId) {
        // 1、当前分组只能关联自己所属分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        // 2、当前分组只能关联别的分组里没有引用的属性
        // 2.1、找到当前分类下的其它分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(
                new QueryWrapper<AttrGroupEntity>()
                        .eq("catelog_id", catelogId)
                        .ne("attr_group_id", attrgroupId)
        );
        List<Long> collect = group
                .stream()
                .map(AttrGroupEntity::getAttrGroupId)
                .collect(Collectors.toList()
                );
        // 2.2、这些分类关联的属性
        List<AttrAttrgroupRelationEntity> groupId = relationDao
                .selectList(new QueryWrapper<AttrAttrgroupRelationEntity>()
                        .in("attr_group_id", collect));
        List<Long> attrIds = groupId
                .stream()
                .map(AttrAttrgroupRelationEntity::getAttrId)
                .collect(Collectors.toList()
                );
        // 2.3、从当前分类的所有属性中移除这些属性
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>()
                .eq("catelog_id", catelogId)
                .notIn("attr_id", attrIds);
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(page);
    }

}